// import { HookContext } from '@/biz-components/hoc-form/with-normal';
import { WithNormalRenderContext } from '@ey-render/hoc-form';
import PageTitle from '@/components/page-title';
import { Card } from 'antd';
import React, { useContext, useMemo } from 'react';
import { FieldGroupProps } from 'schema-form';
import { toJS } from '@formily/reactive';
import './field-item-group.less';
import { getButtons } from '@/utils/with-btns';

const ContentWrap = ({ title, code, buttons }: any) => {
  return <>
    <PageTitle code={code} label={
      buttons?.length > 0 ? <div>{title}<span style={{ marginLeft: 15 }}>{buttons}</span></div> : title
    } />

  </>
}

const dealBtns = (btns: any[]) => {
  const leftBtns: any[] = [];
  const rightBtns: any[] = [];
  if (btns?.length > 0) {
    const buttons = toJS(btns);
    buttons.forEach(btn => {
      if (btn?.props?.position && btn?.props?.position === 'right') {
        rightBtns.push(btn)
      } else {
        leftBtns.push(btn)
      }
    })
  }
  return {
    leftBtns,
    rightBtns
  }
}


export const FieldGroup: React.FC<FieldGroupProps> = ({ children, ...rest }) => {
  const { buttons, code, title } = rest;
  // TODO:获取 ref
  const { hooksRef, loading } = useContext(WithNormalRenderContext);
  const { leftBtns, rightBtns } = useMemo(() => {
    return dealBtns(buttons)
  }, [JSON.stringify(buttons)])
  const getBtns = (btns: any[]) => getButtons({ loading, buttons: btns }, hooksRef?.current);
  return (
    <Card id={rest.code} className="normal__form form__group"
      title={<ContentWrap code={code} title={title} buttons={leftBtns?.length > 0 ? getBtns(leftBtns) : []} />}
      extra={rightBtns?.length > 0 ? getBtns(rightBtns) : []} >
      {children}
    </Card>
  );
}
